<template>
  <a-card
    :tab-list="hideCardTab ? [] : tabList"
    :active-tab-key="titleKey"
    @tabChange="key => onTabChange(key)"
    :bordered="false"
    class="br-10 content"
  >
    <div class="table-operator">
      <a-button v-has="'content:warehouse:add'" type="primary" @click="openUpModal">
        {{ titleKey === fileTypeEnums.IMAGE ? '上传图片' : '上传视频' }}
      </a-button>
      <a-button v-if="hideCardTab" type="link" @click="goWarehouse">
        去管理素材
      </a-button>
    </div>
    <div class="disFlx" style="border: solid 1px #F5F5F5;">
      <GroupTree
        :key="titleKey"
        ref="GroupTree"
        :activeTabKey="titleKey"
        :hideOperate="hideCardTab"
        @onSelect="onSelect"
      />

      <div class="warehouseBody" :style="hideCardTab ? 'min-height: 462px;' : ''">
        <div class="fz-15 fw-7 disFlxJS _pb-10">
          <div>{{ selectedGroup.name || '未分组' }}</div>
          <div v-if="hideCardTab">
            已勾选<span class="colorZS _pl-2 _pr-2 fw-7">{{ checkedIds.length }}</span
            >项
          </div>
        </div>
        <div v-if="total && !hideCardTab" class="disFlxJS _pb-10">
          <div class="disFlxAC">
            <span class="_pr-10 color9"
              >已勾选<span class="colorZS _pl-2 _pr-2 fw-7">{{ checkedIds.length }}</span
              >项</span
            >

            <a-button type="primary" ghost @click="handCheckedAll"
              >{{ checkedIds.length === total ? '取消勾选' : '勾选' }}"分组内"下全部素材</a-button
            >
          </div>
          <div>
            <a-button v-has="'content:warehouse:editGroup'" type="primary" ghost @click="handBatchMove"
              >移动分组</a-button
            >
            <a-button
              v-has="'content:warehouse:remove'"
              type="danger"
              class="_ml-10"
              ghost
              @click="handBatchDelete(checkedIds)"
              >批量删除</a-button
            >
            <!-- <a-button class="_ml-10">批量下载</a-button> -->
          </div>
        </div>
        <a-checkbox-group :value="checkedIds" class="urlListBox" :style="hideCardTab ? 'grid-gap: 5px;' : ''">
          <div v-for="(item, index) in tableData" :key="item.id">
            <ImgOrVideo
              :item="item"
              :type="titleKey === fileTypeEnums.VIDEO ? 'video' : 'image'"
              :preview="!hideCardTab"
              :showDelete="!hideCardTab && checkPermission('content:warehouse:remove')"
              :showDownload="!hideCardTab && checkPermission('content:warehouse:export')"
              :showEdit="!hideCardTab && titleKey === fileTypeEnums.VIDEO && checkPermission('content:warehouse:edit')"
              :width="180"
              :height="180"
              @delete="handBatchDelete([item.id])"
              @edit="handEdit"
              @click="handClick"
            >
              <template slot="checked">
                <a-checkbox :value="item.id" :key="item.id" @change="event => handChecked(event, item)" />
              </template>
            </ImgOrVideo>
            <div v-if="titleKey === fileTypeEnums.VIDEO" class="_pt-5 ov-2">{{ item.name }}</div>
          </div>
        </a-checkbox-group>
        <div class="disFlx flexEnd _pt-20">
          <a-pagination
            showQuickJumper
            showSizeChanger
            :current="currentPage"
            :pageSize="currentSize"
            :total="total"
            :show-total="total => `共 ${total} 条，当前显示第${currentPage}页`"
            :size="hideCardTab ? 'small' : 'default'"
            @change="changePagination"
            @showSizeChange="changePagination"
          />
        </div>


        <a-empty v-if="!tableData.length && !tableLoading" class="_mt-50 _mb-50" />
      </div>
    </div>

    <UpModal ref="UpModal" :activeTabKey="titleKey" @refresh="upSuccess" />

    <template v-if="!hideCardTab">
      <MoveGroup ref="MoveGroup" :activeTabKey="titleKey" :checkedIds="checkedIds" @refresh="resetAll" />
      <VideoPlay ref="VideoPlay" />
    </template>
  </a-card>
</template>

<script>
import ImgOrVideo from '@/components/ImgOrVideo'
import VideoPlay from '@/components/ImgOrVideo/videoPlay'
import GroupTree from './components/groupTree'
import UpModal from './components/upModal'
import MoveGroup from './components/moveGroup'
import { fileTypeEnums } from '@/enums/content'
import { getWarehouseList, checkedAllWarehouse, deleteWarehouse } from '@/api/content/warehouse'
import { uniq, uniqBy, difference, differenceBy } from 'lodash-es'
import { checkPermission } from '@/utils/authority'

export default {
  components: {
    ImgOrVideo,
    VideoPlay,
    GroupTree,
    UpModal,
    MoveGroup
  },
  props: {
    // 隐藏tabs切换-弹窗进入
    hideCardTab: {
      type: Boolean,
      default: false
    },
    // 限制素材库勾选数量 0则不限制
    limit: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      fileTypeEnums,
      tabList: [
        {
          key: fileTypeEnums.IMAGE,
          tab: '图片'
        },
        {
          key: fileTypeEnums.VIDEO,
          tab: '视频'
        }
      ],
      titleKey: fileTypeEnums.IMAGE,
      selectedGroup: {}, // 选中分组
      tableLoading: true,
      currentPage: 1, // 当前页数
      currentSize: 10, // 当前条数
      total: 0, // 总数
      tableData: [],
      checkedIds: [], // 选中ID
      checkedRows: [] // 选择素材,不支持全选,应用于素材库弹窗
    }
  },
  methods: {
    checkPermission,
    onTabChange(key) {
      this.titleKey = key
    },
    reset() {
      const that = this
      that.currentPage = 1
      that.currentSize = 10
      that.checkedIds = []
      that.checkedRows = []

      that.getList()
    },
    resetAll() {
      this.reset()
      this.$refs.GroupTree.getWarehouseGroupList()
    },
    upSuccess() {
      this.getList()
      this.$refs.GroupTree.getWarehouseGroupList() // 刷新左侧数量
    },
    // 左侧tree选中
    onSelect(group) {
      this.selectedGroup = group
      this.reset()
    },
    async getList() {
      this.tableLoading = true
      const { data } = await getWarehouseList({
        type: this.titleKey,
        groupId: this.selectedGroup.id,
        current: this.currentPage,
        size: this.currentSize
      }).catch(() => (this.tableLoading = false))
      this.tableData = data.records
      this.total = data.total
      this.tableLoading = false
    },

    // 上传图片 || 视频
    openUpModal() {
      this.$refs.UpModal.show(this.selectedGroup.id)
    },

    // 分页跳转
    changePagination(page, pageSize) {
      this.currentPage = page
      this.currentSize = pageSize
      this.getList()
    },
    // 全选
    async handCheckedAll() {
      this.checkedRows = []
      if (this.total === this.checkedIds.length) {
        this.checkedIds = []
      } else {
        const { data } = await checkedAllWarehouse({ type: this.titleKey, groupId: this.selectedGroup.id })
        this.checkedIds = data
      }
    },
    // 点击封面图
    handClick(item) {
      let event = {
        target: {
          checked: !this.checkedIds.includes(item.id),
          value: item.id
        }
      }
      this.handChecked(event, item)
    },
    handChecked(event, item) {
      const that = this
      const { target } = event
      if (target.checked) {
        that.checkedIds = uniq([...that.checkedIds, target.value])
        that.checkedRows = uniqBy([...that.checkedRows, item])
      } else {
        that.checkedIds = difference(that.checkedIds, [target.value]) // 从已勾选处删除
        that.checkedRows = differenceBy(that.checkedRows, [item], 'id')
      }

      // 存在限制勾选
      if(that.limit > 0){
        that.checkedIds = that.checkedIds.slice(-that.limit)
        that.checkedRows = that.checkedRows.slice(-that.limit)
      }
    },
    handBatchDelete(ids) {
      const that = this
      if (!ids.length) {
        that.$message.error('请勾选需要操作的素材')
        return
      }
      that.$confirm({
        title: `确定要删除选中的${ids.length}${that.titleKey === fileTypeEnums.IMAGE ? '张图片' : '个视频'}？`,
        content: `将从素材中心将${
          that.titleKey === fileTypeEnums.IMAGE ? '图片' : '视频'
        }删除！已使用的场景不会被影响。`,
        centered: true,
        onOk() {
          return new Promise((resolve, reject) => {
            deleteWarehouse({ delIds: ids })
              .then(res => {
                that.checkedIds = difference(that.checkedIds, ids) // 从已勾选处删除
                that.$message.success('删除成功')
                that.resetAll()
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
          })
        }
      })
    },
    handEdit(row) {
      this.$refs.UpModal.show(row.materialCenterGroupId, row)
    },
    handBatchMove() {
      const that = this
      if (!that.checkedIds.length) {
        that.$message.error('请勾选需要操作的素材')
        return
      }
      that.$refs.MoveGroup.show()
    },
    // 跳转素材管理页面
    goWarehouse() {
      this.$router.push({ path: `/content/warehouse` })
      this.$emit('closeModal')
    }
  }
}
</script>

<style lang="less" scoped>
.warehouseBody {
  padding: 10px;
  flex: 1;
  .urlListBox {
    display: grid;
    grid-gap: 20px;
    grid-template-columns: repeat(auto-fill, 180px);
  }
}
</style>
